package com.gozap.collection;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class TestArrayBlockingQueue {
	
	/** 当数组已经满了的时候，如果多个数据继续同时添加，谁将会先天加进去 */
	@Test
	public void testMultiAdd() throws Exception{
		ArrayBlockingQueue<String> queue=new ArrayBlockingQueue<String>(3);
		new Thread(new TakeThread(queue)).start();
		queue.put("1");
		queue.put("2");
		queue.put("3");
		new Thread(new PutThread(queue,"4")).start();
		TimeUnit.MILLISECONDS.sleep(10);
		new Thread(new PutThread(queue,"5")).start();
		TimeUnit.MILLISECONDS.sleep(10);
		new Thread(new PutThread(queue,"6")).start();
		TimeUnit.SECONDS.sleep(5);
		System.out.println(queue);
	}
	
	class TakeThread implements Runnable{
		ArrayBlockingQueue<String> queue;
		
		public TakeThread(ArrayBlockingQueue<String> queue){
			this.queue=queue;
		}

		int count=0;
		public void run() {
			
			while(!queue.isEmpty()&&count!=4){
				
				try {
					TimeUnit.MILLISECONDS.sleep(1000);
					System.out.println("sleep enough");
					System.out.println(queue.take());
					count++;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	class PutThread implements Runnable{
		ArrayBlockingQueue<String> queue;
		private String value;
		
		public PutThread(ArrayBlockingQueue<String> queue,String value){
			this.queue=queue;
			this.value=value;
		}

		public void run() {
				try {
					queue.put(value);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
	}
}
